package com.hht.wblib.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Map;

public class GsonHelper {

    // Private constructor to prevent instantiation from outside the class.
    private GsonHelper() {}

    /**
     * A static inner class that holds the single instance of GsonHelper.
     */
    private static class SingletonHolder {
        private static final GsonHelper INSTANCE = new GsonHelper();
    }

    /**
     * Returns the single instance of GsonHelper.
     */
    public static GsonHelper getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static final Gson gson = new Gson();

    /**
     * Converts an object to JSON string.
     */
    public String beanToString(Object any) {
        return gson.toJson(any);
    }

    /**
     * Converts a JSON string to a bean.
     */
    public <T> T stringToBean(String gsonString, Class<T> cls) {
        return gson.fromJson(gsonString, cls);
    }

    /**
     * Converts a JSON string to a list of objects, potentially causing type erasure issues.
     */
    @SuppressWarnings("unchecked")
    public <T> ArrayList<T> stringToList(String gsonString) {
        Type listType = new TypeToken<ArrayList<T>>() {}.getType();
        return gson.fromJson(gsonString, listType);
    }

    /**
     * Converts a JSON string to a map.
     */
    @SuppressWarnings("unchecked")
    public <T> Map<String, T> stringToMaps(String gsonString, Class<T> cls) {
        Type mapType = new TypeToken<Map<String, T>>() {}.getType();
        return gson.fromJson(gsonString, mapType);
    }
}